iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
Software Development

從零開始學 Python系列 第 14

Day 14 – 小挑戰!製作隨機密碼產生器

  • 分享至 

  • xImage
  •  

今天的挑戰目標

  • 結合前一天學到的 random 模組
  • 使用字串操作(string 模組)
  • 製作一個可以自訂長度的隨機密碼產生器

一、基本版:隨機密碼產生器

import random
import string

def generate_password(length=8):
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))

print("你的隨機密碼:", generate_password(12))

說明:

  • string.ascii_letters = 包含大小寫英文字母
  • string.digits = 數字 0~9
  • random.choice() = 從字元池中隨機挑選

產生由「字母 + 數字」組成的密碼:
螢幕擷取畫面 2025-08-15 173955

二、進階版隨機密碼

需求:

  • 至少包含 大寫字母、小寫字母、數字、符號
  • 使用者可以指定密碼長度
  • 密碼順序必須隨機打亂
import random
import string

def generate_password(length=12):
    if length < 4:
        raise ValueError("密碼長度必須至少為 4 才能包含所有類型字符")

    # 至少包含各種類型 1 個
    password = [
        random.choice(string.ascii_uppercase),  # 大寫
        random.choice(string.ascii_lowercase),  # 小寫
        random.choice(string.digits),           # 數字
        random.choice(string.punctuation)       # 符號
    ]

    # 剩餘的隨機填充
    all_chars = string.ascii_letters + string.digits + string.punctuation
    password += [random.choice(all_chars) for _ in range(length - 4)]

    # 打亂順序
    random.shuffle(password)

    return ''.join(password)

print("你的隨機密碼:", generate_password(12))

說明:

  • string.ascii_uppercase = 大寫 A–Z
  • string.ascii_lowercase = 小寫 a–z
  • string.punctuation = 常見標點符號(!@#$%^&*...)
  • random.shuffle() = 打亂密碼字元順序
    螢幕擷取畫面 2025-08-16 131414

學習心得

今天的挑戰很有趣!把之前學過的隨機數、字串操作、函式都結合起來,真的做出了一個有用的小工具!
明天要進入第十五天!字串的進階操作!會學到字串的更多方法,例如搜尋、取代、分割、大小寫轉換等,讓文字處理變得更靈活!


上一篇
Day 13 – 模組(import)與 math / random
下一篇
Day 15 – 字串處理:split、replace、format、f-string
系列文
從零開始學 Python30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言